package com.sakura.二叉树;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;

public class Code199_二叉树的右视图 {

    private static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
    public List<Integer> rightSideView(TreeNode root) {
       List<Integer> ans = new ArrayList<>();
       if (root == null) {
           return ans;
       }
        ArrayDeque<TreeNode> queue = new ArrayDeque<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            while (size-- > 0) {
                TreeNode cur = queue.poll();
                // 如果队列中已经是最后一个结果集，说明这个节点就是当前层最后一个节点 一定能被看到
                if (size == 0) {
                    ans.add(cur.val);
                }
                if (cur.left != null) {
                    queue.offer(cur.left);
                }
                if (cur.right != null) {
                    queue.offer(cur.right);
                }
            }
        }
        return ans;
    }
}
